package aggregate.aggregator;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;

import aggregate.aggregator.remote.Category;
import aggregate.aggregator.remote.Client;
import aggregate.aggregator.remote.ContentItem;

public class Channel {
	private Category category;
	
	public Channel(Category category) {
		this.category = category;
	}

	public void verifyUpdates(Connection con, Database db, List<Feed> feeds, List<Client> clients) throws SQLException
	{
		int numberOfUpdates = 0, feedUpdates;
		Feed feed;
		ContentItem item;
		Vector<ContentItem> totalUpdates = new Vector<ContentItem>();
		Iterator<Feed> iterator = feeds.listIterator();
		Iterator<Client> iter = clients.iterator();
		while(iterator.hasNext())
		{
			feed = (Feed) iterator.next();
			feedUpdates = feed.verifyUpdates();
			if(feedUpdates != 0)
			{
				ListIterator<ContentItem> i = feed.getUpdates().listIterator();
				while(i.hasNext())
				{
					item = (ContentItem) i.next();
					totalUpdates.add(item);
					item.setCategoryId(category.getId());
					db.insertContent(con, item);
				}
				feed.setLastNewsTitle();
				db.updateLastNewsForFeed(con, feed);
			}
			numberOfUpdates += feedUpdates;
			
		}
		if(numberOfUpdates != 0)
		{	
			while(iter.hasNext())
			{
				try {
					((Client) iter.next()).notify(totalUpdates);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
			
		}
		
	}
}
